<template>
  <div class="staff-container">
    <div class="page-header">
      <h2 class="page-title">工作人员管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateStaff">
          <el-icon><Plus /></el-icon>新增工作人员
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>
    
    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="姓名">
          <el-input v-model="filterForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="窗口">
          <el-select v-model="filterForm.windowId" placeholder="请选择窗口" clearable>
            <el-option
              v-for="item in windowList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 工作人员表格 -->
    <div class="staff-table">
      <el-table
        :data="staffList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="150" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column prop="windowName" label="所属窗口" min-width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="handleEditStaff(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="info"
              @click="handleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDeleteStaff(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建/编辑工作人员对话框 -->
    <el-dialog
      v-model="staffDialog.visible"
      :title="staffDialog.isEdit ? '编辑工作人员' : '新增工作人员'"
      width="600px"
    >
      <el-form
        ref="staffFormRef"
        :model="staffForm"
        :rules="staffRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="staffForm.username" 
            placeholder="请输入用户名" 
            :disabled="staffDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="staffForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="staffForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="staffForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="所属窗口" prop="windowId">
          <el-select v-model="staffForm.windowId" placeholder="请选择窗口" style="width: 100%">
            <el-option
              v-for="item in windowList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!staffDialog.isEdit">
          <el-input 
            v-model="staffForm.password" 
            placeholder="请输入密码" 
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="staffForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="staffDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitStaffForm">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 重置密码结果对话框 -->
    <el-dialog
      v-model="resetPasswordDialog.visible"
      title="重置密码成功"
      width="400px"
    >
      <div class="reset-password-result">
        <p>新密码已生成，请妥善保管并及时通知用户更改</p>
        <div class="new-password">
          <span>新密码：</span>
          <el-tag size="large">{{ resetPasswordDialog.newPassword }}</el-tag>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="resetPasswordDialog.visible = false">确定</el-button>
        <el-button type="info" @click="copyPassword">复制密码</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

export default {
  name: 'StaffList',
  components: {
    Plus,
    Refresh,
    Search
  },
  setup() {
    // 模拟窗口数据
    const mockWindows = [
      { id: 1, name: '1号窗口' },
      { id: 2, name: '2号窗口' },
      { id: 3, name: '3号窗口' },
      { id: 4, name: '4号窗口' },
      { id: 5, name: '自助服务区' }
    ]
    
    // 模拟工作人员数据
    const mockStaffs = [
      {
        id: 1,
        username: 'zhangsan',
        name: '张三',
        phone: '13800138001',
        email: 'zhangsan@example.com',
        windowId: 1,
        windowName: '1号窗口',
        status: 1,
        createTime: '2023-01-05 10:30:22'
      },
      {
        id: 2,
        username: 'lisi',
        name: '李四',
        phone: '13800138002',
        email: 'lisi@example.com',
        windowId: 2,
        windowName: '2号窗口',
        status: 1,
        createTime: '2023-01-06 14:22:35'
      },
      {
        id: 3,
        username: 'wangwu',
        name: '王五',
        phone: '13800138003',
        email: 'wangwu@example.com',
        windowId: 3,
        windowName: '3号窗口',
        status: 1,
        createTime: '2023-01-08 09:15:40'
      },
      {
        id: 4,
        username: 'zhaoliu',
        name: '赵六',
        phone: '13800138004',
        email: 'zhaoliu@example.com',
        windowId: 4,
        windowName: '4号窗口',
        status: 0,
        createTime: '2023-01-10 16:45:12'
      },
      {
        id: 5,
        username: 'qianqi',
        name: '钱七',
        phone: '13800138005',
        email: 'qianqi@example.com',
        windowId: 5,
        windowName: '自助服务区',
        status: 1,
        createTime: '2023-01-12 11:20:38'
      }
    ]
    
    // 窗口列表
    const windowList = ref([...mockWindows])
    
    // 工作人员列表
    const staffList = ref([...mockStaffs])
    const tableLoading = ref(false)
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: mockStaffs.length
    })
    
    // 过滤表单
    const filterForm = reactive({
      name: '',
      username: '',
      windowId: '',
      status: ''
    })
    
    // 工作人员对话框
    const staffDialog = reactive({
      visible: false,
      isEdit: false
    })
    
    // 重置密码对话框
    const resetPasswordDialog = reactive({
      visible: false,
      newPassword: ''
    })
    
    // 工作人员表单
    const staffFormRef = ref(null)
    const staffForm = reactive({
      id: null,
      username: '',
      name: '',
      phone: '',
      email: '',
      windowId: '',
      password: '',
      status: 1
    })
    
    // 表单验证规则
    const staffRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      windowId: [
        { required: true, message: '请选择窗口', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 根据筛选条件和分页显示工作人员列表
    const displayStaffList = computed(() => {
      // 应用筛选条件
      let filteredList = staffList.value.filter(item => {
        let nameMatch = true, usernameMatch = true, windowMatch = true, statusMatch = true
        
        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }
        
        if (filterForm.username) {
          usernameMatch = item.username.includes(filterForm.username)
        }
        
        if (filterForm.windowId) {
          windowMatch = item.windowId === filterForm.windowId
        }
        
        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }
        
        return nameMatch && usernameMatch && windowMatch && statusMatch
      })
      
      // 更新总数
      pagination.total = filteredList.length
      
      // 应用分页
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      
      return filteredList.slice(start, end)
    })
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
    }
    
    // 重置过滤器
    const resetFilter = () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = ''
      })
      pagination.currentPage = 1
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
    }
    
    // 处理刷新
    const handleRefresh = () => {
      tableLoading.value = true
      setTimeout(() => {
        tableLoading.value = false
        ElMessage.success('刷新成功')
      }, 500)
    }
    
    // 处理新建工作人员
    const handleCreateStaff = () => {
      staffDialog.isEdit = false
      staffDialog.visible = true
      
      Object.keys(staffForm).forEach(key => {
        if (key === 'status') {
          staffForm[key] = 1
        } else {
          staffForm[key] = ''
        }
      })
    }
    
    // 处理编辑工作人员
    const handleEditStaff = (row) => {
      staffDialog.isEdit = true
      staffDialog.visible = true
      
      staffForm.id = row.id
      staffForm.username = row.username
      staffForm.name = row.name
      staffForm.phone = row.phone
      staffForm.email = row.email
      staffForm.windowId = row.windowId
      staffForm.status = row.status
    }
    
    // 处理删除工作人员
    const handleDeleteStaff = (row) => {
      ElMessageBox.confirm(`确定要删除工作人员"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中删除对应工作人员
        const index = staffList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          staffList.value.splice(index, 1)
          ElMessage.success('删除工作人员成功')
        }
      }).catch(() => {})
    }
    
    // 处理切换状态
    const handleToggleStatus = (row) => {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      
      ElMessageBox.confirm(`确定要${statusText}工作人员"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中更新状态
        const index = staffList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          staffList.value[index].status = newStatus
          ElMessage.success(`${statusText}工作人员成功`)
        }
      }).catch(() => {})
    }
    
    // 处理重置密码
    const handleResetPassword = (row) => {
      ElMessageBox.confirm(`确定要重置工作人员"${row.name}"的密码吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 生成随机密码
        const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
        let password = ''
        for (let i = 0; i < 8; i++) {
          password += chars.charAt(Math.floor(Math.random() * chars.length))
        }
        
        // 显示重置密码对话框
        resetPasswordDialog.newPassword = password
        resetPasswordDialog.visible = true
        
        // 在实际应用中，这里应该调用API将新密码保存到数据库
      }).catch(() => {})
    }
    
    // 复制密码
    const copyPassword = () => {
      const input = document.createElement('input')
      input.value = resetPasswordDialog.newPassword
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      ElMessage.success('密码已复制到剪贴板')
    }
    
    // 提交工作人员表单
    const submitStaffForm = () => {
      staffFormRef.value.validate((valid) => {
        if (valid) {
          const isEdit = staffDialog.isEdit
          
          if (isEdit) {
            // 编辑现有工作人员
            const index = staffList.value.findIndex(item => item.id === staffForm.id)
            if (index !== -1) {
              // 获取窗口名称
              const window = windowList.value.find(w => w.id === staffForm.windowId)
              const windowName = window ? window.name : ''
              
              staffList.value[index] = {
                ...staffList.value[index],
                name: staffForm.name,
                phone: staffForm.phone,
                email: staffForm.email,
                windowId: staffForm.windowId,
                windowName: windowName,
                status: staffForm.status,
              }
              ElMessage.success('更新工作人员成功')
            }
          } else {
            // 创建新工作人员
            const newId = Math.max(...staffList.value.map(item => item.id), 0) + 1
            const now = new Date()
            const createTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
            
            // 获取窗口名称
            const window = windowList.value.find(w => w.id === staffForm.windowId)
            const windowName = window ? window.name : ''
            
            staffList.value.push({
              id: newId,
              username: staffForm.username,
              name: staffForm.name,
              phone: staffForm.phone,
              email: staffForm.email,
              windowId: staffForm.windowId,
              windowName: windowName,
              status: staffForm.status,
              createTime: createTime
            })
            ElMessage.success('创建工作人员成功')
          }
          
          staffDialog.visible = false
        }
      })
    }
    
    onMounted(() => {
      // 初始化时不需要额外操作，模拟数据已加载
    })
    
    return {
      staffList: displayStaffList,
      windowList,
      tableLoading,
      pagination,
      filterForm,
      staffDialog,
      staffFormRef,
      staffForm,
      staffRules,
      resetPasswordDialog,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleCreateStaff,
      handleEditStaff,
      handleDeleteStaff,
      handleToggleStatus,
      handleResetPassword,
      copyPassword,
      submitStaffForm
    }
  }
}
</script>

<style scoped>
.staff-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.staff-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.reset-password-result {
  text-align: center;
  padding: 20px 0;
}

.reset-password-result p {
  margin-bottom: 15px;
  color: #606266;
}

.new-password {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.new-password span {
  margin-right: 10px;
  font-weight: bold;
}

.new-password .el-tag {
  font-size: 16px;
  padding: 8px 12px;
  letter-spacing: 1px;
}
</style> 